import uniPromisify from '@/util/uniPromisify'

export const onLaunchPromise = new Promise((resolve) => {
  // eslint-disable-next-line no-use-before-define
  onLaunchPromise_resolve = resolve
})

export let onLaunchPromise_resolve

/**
 * 下载图片到相册
 * @param {*} url
 * @returns
 */
export async function downImgToAlbum(url) {
  let localUrl
  try {
    const res = await uniPromisify.downloadFile({ url })
    console.log('dlf res', res)
    if (res.errMsg !== 'downloadFile:ok') {
      return
    }
    localUrl = res.tempFilePath
    await uniPromisify.saveImageToPhotosAlbum({
      filePath: localUrl
    })
    uniPromisify.showToast({
      title: '已保存至相册'
    })
  } catch (error) {
    console.log('err', error)
    if (error.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
      const settingRes = await modalForSetting({ content: '请授权保存图片', scope: 'scope.writePhotosAlbum' })
      if (settingRes) {
        try {
          await uniPromisify.saveImageToPhotosAlbum({
            filePath: localUrl
          })
        } catch (error) {
          console.log(error)
        }
      }
      // 'scope.writePhotosAlbum'
    }
  }
}

/**
 * 提示去授权
 * @param {*} param0
 * content, title = '提示', scope e.g. scope.writePhotosAlbum
 * @returns boolen: 获得授权
 */
export async function modalForSetting({ content, title = '提示', scope }) {
  try {
    const res = await uniPromisify.showModal({
      title,
      content
    })
    if (res.confirm) {
      const settingRes = await uniPromisify.openSetting()
      return settingRes.authSetting[scope]
    }
    return false
  } catch (error) {
    console.log(error)
  }
}
